package com.huixuebao.common.util;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class ConvertUtils {

    public static <T, D> IPage<D> convertToDTOPage(IPage<T> entityPage, Class<D> clazz) {
        IPage<D> dtoPage = new Page<>();
        BeanUtil.copyProperties(entityPage, dtoPage, "records", "optimizeCountSql");
        List<D> dtoRecords = entityPage.getRecords().stream().map(entity -> convertToDTO(entity, clazz)).collect(Collectors.toList());
        dtoPage.setRecords(dtoRecords);
        return dtoPage;
    }

    public static <T, D> D convertToDTO(T entity, Class<D> clazz) {
        try {
            D dto = clazz.newInstance();
            BeanUtil.copyProperties(entity, dto);
            return dto;
        } catch (Exception e) {
            log.info("PageUtil#convertToDTOPage", e);
            throw new RuntimeException(e.getMessage());
        }
    }

    public static <T, D> List<D> convertToDTOList(List<T> list , Class<D> clazz) {
        return list.stream().map(entity -> convertToDTO(entity, clazz)).collect(Collectors.toList());
    }


}
